﻿using BLL.TicketBLL;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MDMUI.TicketManagement
{
    public partial class SubmitTicket : Form
    {
        private TicketCreationBLL _ticketBLL = new TicketCreationBLL();
        private DataGridViewRow _selectedRow;
        public SubmitTicket()
        {
            InitializeComponent();
            InitializeDataGridView();
            this.Shown += (s, e) => LoadWorkOrders(); // 等待窗体完全显示后再加载
        }

        // 修改InitializeDataGridView方法 - 修复列名显示
        private void InitializeDataGridView()
        {
            工单清单DGV.AutoGenerateColumns = false;
            工单清单DGV.Columns.Clear();

            // 使用完整列名和中文标题
            var columns = new (string Name, string HeaderText, int Width, string Format)[]
            {
                ("WorkOrderId", "工单ID", 80, ""),
                ("ProductId", "产品ID", 80, ""),
                ("WorkOrderType", "工单类型", 100, ""),
                ("DetailedType", "详细类型", 80, ""),
                ("WorkOrderDescription", "工单说明", 150, ""),
                ("WorkOrderStatus", "工单状态", 80, ""),
                ("PlannedStartDate", "计划开始日期", 150, "yyyy-MM-dd HH:mm"),
                ("PlannedDueDate", "计划结束日期", 150, "yyyy-MM-dd HH:mm"),
                ("TestProgramNumber", "测试程序号", 80, ""),
                ("CompanyNumber", "公司ID", 80, ""),
                ("ProductType", "产品类型", 120, ""),
                ("TotalProcessId", "工艺流程号", 120, "")
            };

            foreach (var col in columns)
            {
                DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn
                {
                    Name = col.Name,
                    HeaderText = col.HeaderText,
                    Width = col.Width,
                    DataPropertyName = col.Name
                };

                if (!string.IsNullOrEmpty(col.Format))
                {
                    column.DefaultCellStyle.Format = col.Format;
                }

                工单清单DGV.Columns.Add(column);
            }

            工单清单DGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            工单清单DGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        }

        // 修改LoadWorkOrders方法 - 修复线程问题和绑定方式
        private void LoadWorkOrders()
        {
            try
            {
                // 确保窗口句柄已创建
                if (!this.IsHandleCreated) return;

                List<Dictionary<string, object>> workOrders = _ticketBLL.GetAllWorkOrdersWithProduct();
                // 调试输出
                Debug.WriteLine($"获取到 {workOrders?.Count ?? 0} 条记录");
                if (workOrders?.Count > 0)
                {
                    var first = workOrders[0];
                    Debug.WriteLine($"首条记录: {string.Join(", ", first.Select(kv => $"{kv.Key}={kv.Value}"))}");
                }

                // 将字典列表转换为DataTable
                DataTable table = new DataTable();
                if (workOrders?.Count > 0)
                {
                    // 创建列（确保列名正确）
                    foreach (var key in workOrders[0].Keys)
                    {
                        table.Columns.Add(key.ToString());
                    }

                    // 添加行数据
                    foreach (var dict in workOrders)
                    {
                        DataRow row = table.NewRow();
                        foreach (var pair in dict)
                        {
                            row[pair.Key] = pair.Value;
                        }
                        table.Rows.Add(row);
                    }
                }

                // 使用BeginInvoke确保线程安全
                this.BeginInvoke((MethodInvoker)delegate
                {
                    工单清单DGV.DataSource = table;

                    // 应用日期格式（如果转换中丢失）
                    foreach (DataGridViewColumn column in 工单清单DGV.Columns)
                    {
                        if (column.Name.Contains("Date"))
                        {
                            column.DefaultCellStyle.Format = "yyyy-MM-dd HH:mm";
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载工单失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 查询按钮的点击事件
        private void 查询btn_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取查询条件
                string workOrderId = 工单号txtBox1.Text.Trim();
                string productId = 产品编号txtBox.Text.Trim();
                DateTime? startDate = 开始dateTime.Value;
                DateTime? endDate = 结束dateTime.Value;

                // 验证日期范围
                if (startDate.HasValue && endDate.HasValue && startDate > endDate)
                {
                    MessageBox.Show("开始日期不能晚于结束日期", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 输入验证
                if (string.IsNullOrEmpty(workOrderId) &&
                    string.IsNullOrEmpty(productId) &&
                    !startDate.HasValue &&
                    !endDate.HasValue)
                {
                    MessageBox.Show("请输入至少一个查询条件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 执行条件查询
                List<Dictionary<string, object>> result =
                    _ticketBLL.GetWorkOrdersWithProductByCondition(
                        workOrderId,
                        productId,
                        startDate,
                        endDate);

                if (result == null || result.Count == 0)
                {
                    MessageBox.Show("未找到匹配的工单", "查询结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    工单清单DGV.DataSource = null; // 清空数据网格
                    return;
                }

                // 转换为DataTable
                DataTable table = new DataTable();

                // 创建列
                foreach (var key in result[0].Keys)
                {
                    table.Columns.Add(key.ToString());
                }

                // 添加行数据
                foreach (var dict in result)
                {
                    DataRow row = table.NewRow();
                    foreach (var pair in dict)
                    {
                        row[pair.Key] = pair.Value;
                    }
                    table.Rows.Add(row);
                }

                // 绑定到DataGridView
                工单清单DGV.DataSource = table;

                // 应用日期格式
                foreach (DataGridViewColumn column in 工单清单DGV.Columns)
                {
                    if (column.Name.Contains("Date"))
                    {
                        column.DefaultCellStyle.Format = "yyyy-MM-dd HH:mm";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void 取消工单btn_Click(object sender, EventArgs e)
        {
            // 获取选中的行
            DataGridViewSelectedRowCollection selectedRows = 工单清单DGV.SelectedRows;

            if (selectedRows.Count == 0)
            {
                MessageBox.Show("请先选中要取消的工单行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 确认删除操作
            if (MessageBox.Show("确定要取消选中的工单吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                return;
            }

            DataTable dataTable = (DataTable)工单清单DGV.DataSource;

            foreach (DataGridViewRow row in selectedRows)
            {
                // 获取选中行的主键（假设“WorkOrderId”是主键）
                string workOrderId = row.Cells["WorkOrderId"].Value?.ToString();

                // 如果需要同步到后端或数据库，请在此处调用业务逻辑层方法
                _ticketBLL.CancelWorkOrder(workOrderId);

                // 从DataTable中删除行
                DataRow[] dataRows = dataTable.Select($"WorkOrderId = '{workOrderId}'");
                foreach (DataRow dr in dataRows)
                {
                    dr.Delete();
                }
            }
            // 刷新DataGridView显示
            工单清单DGV.Refresh();
        }


        // DataGridView 行选择事件
        private void 工单清单DGV_SelectionChanged(object sender, EventArgs e)
        {
            if (工单清单DGV.SelectedRows.Count > 0)
            {
                _selectedRow = 工单清单DGV.SelectedRows[0]; // 获取选中的行
                // 填充工单号到文本框
                工单号txtBox2.Text = _selectedRow.Cells["WorkOrderId"].Value?.ToString() ?? string.Empty;
                // 填充当前的 TotalProcessId 到工艺流程号文本框
                工艺流程号txtBox1.Text = _selectedRow.Cells["TotalProcessId"].Value?.ToString() ?? string.Empty;
            }
        }

        // 变更工艺流按钮点击事件
        private void 变更工艺流btn_Click(object sender, EventArgs e)
        {
            if (_selectedRow == null)
            {
                MessageBox.Show("请先选中要修改的工单行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 获取工单 ID 和新的工艺流程号
            string workOrderIdStr = 工单号txtBox2.Text.Trim();
            string newTotalProcessIdStr = 工艺流程号txtBox1.Text.Trim();

            if (string.IsNullOrEmpty(workOrderIdStr))
            {
                MessageBox.Show("工单号不能为空", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrEmpty(newTotalProcessIdStr))
            {
                MessageBox.Show("工艺流程号不能为空", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            int workOrderId;
            int newTotalProcessId;

            // 验证输入是否为整数
            if (!int.TryParse(workOrderIdStr, out workOrderId))
            {
                MessageBox.Show("工单号必须是有效的整数", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!int.TryParse(newTotalProcessIdStr, out newTotalProcessId))
            {
                MessageBox.Show("工艺流程号必须是有效的整数", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 调用业务逻辑层方法更新工艺流程号
            try
            {
                int updatedRows = _ticketBLL.UpdateTotalProcessId(workOrderId, newTotalProcessId);
                if (updatedRows > 0)
                {
                    // 更新成功，刷新 DataGridView 当前行的 TotalProcessId
                    _selectedRow.Cells["TotalProcessId"].Value = newTotalProcessId;
                    MessageBox.Show("工艺流程号更新成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("工艺流程号更新失败", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新工艺流程号失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void 确认btn_Click(object sender, EventArgs e)
        {
            int WorkOrderId = int.Parse(工单号txtBox2.Text);
            WorkOrder workOrder = _ticketBLL.GetWorkOrderById(WorkOrderId);

            if (string.IsNullOrEmpty(用户编号txtBox.Text) || string.IsNullOrEmpty(备注txtBox.Text))
            {
                MessageBox.Show("备注或用户编号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                用户编号txtBox.Focus();
                备注txtBox.Focus();
                return;
            }
            else if (用户编号txtBox.Text != null && 备注txtBox.Text != null)
            {
                workOrder.WorkOrderStatus = "已投单";
                int result = _ticketBLL.UpdateWorkOrderStatus(workOrder);
                MessageBox.Show("受影响的行数", result.ToString());
            }
        }
    }
}